/**
 *  Platypus: Page Layout and Typesetting Software (free at platypus.pz.org)
 *
 *  Platypus is (c) Copyright 2012 Pacific Data Works LLC. All Rights Reserved.
 *  Licensed under Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0.html)
 */
package org.pz.platypus.parser;

import org.pz.platypus.GDD;

import static com.google.common.base.Preconditions.*;

/**
 * @author alb
 */
public class MacroNameExtractor
{
    /**
     * Extract the macro name from the string of chars starting at parsePoint (which points to the char[0] of macro)
     * @param input the chars from which to extract the macro. should begin with a $
     * @param parsePoint the point in input where the extracting should begin
     * @param gdd used for messages
     * @throws IllegalArgumentException in the event of an invalid macro name
     * @return the macro name if all went well; null, if not.
     */
    public String getName( final char[] input, int parsePoint, GDD gdd )
            throws IllegalArgumentException
    {
        checkNotNull( gdd );
        checkNotNull( input, gdd.getLit( "ERROR.PARAM_IN_MACRONAMEEXTRACTOR" ));
        checkArgument( parsePoint >= 0 && parsePoint < input.length, gdd.getLit( "ERROR.PARAM_IN_MACRONAMEEXTRACTOR" ));

        StringBuilder macro = new StringBuilder( input.length );
        int i;

        for( i = parsePoint; i < input.length; i++ )
        {
            if ( Character.isLetterOrDigit( input[i] ) || input[i] == '_' ) {
                macro.append( input[i] );
            }
            else {
                break;
            }
        }

        if ( input[i] != ']' ) {
            gdd.log.warning( gdd.getLit( "INVALID_MACRO_NAME" ) + " " +  macro.toString() + gdd.getLit( "IGNORED" ));
            throw new IllegalArgumentException( macro.toString() );
        }

        return( macro.toString() );
    }
}
